package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-24
 * Time: 22:12
 */

/**
 * 客户端的整体流程:
 * 1:从控制台读取字符串
 * 2:把字符串发送给服务器
 * 3:从服务器读取到响应
 * 4:把响应打印到控制台上
 */
public class UdpEchoClient {
    private    DatagramSocket socket = null;
     private String ip;
     private int port;
    public  UdpEchoClient(String ip,int port) throws SocketException {
        socket = new DatagramSocket();
        this.ip=ip;
        this.port=port;

    }
    public void start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner =new Scanner(System.in);
        while(true){

            String request  = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,
                    request.getBytes().length, InetAddress.getByName(ip),port
                    );
            /**
             * InetAddress.getByName(ip)
             * 需要把字符串格式的ip地址转成Java能识别的对象
             * InetAddress对象,提供了getBYName工厂方法,把上述的字符串格式的ip地址,
             * 转成Java能识别的InetAddress对象了
             *
             */

            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();

    }
}
